package io.kiki.sba.registry.server.clientInterface.wrapper;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.api.Server;
import io.kiki.sba.registry.api.exchange.DataExchanger;
import io.kiki.sba.registry.api.exchange.RequestChannelClosedException;
import io.kiki.sba.registry.common.model.store.BaseInfo;
import io.kiki.sba.registry.common.model.wrapper.WrapperInterceptor;
import io.kiki.sba.registry.common.model.wrapper.WrapperInvocation;
import io.kiki.sba.registry.server.clientInterface.bootstrap.Config;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * check connect already existed
 */
public class ClientCheckWrapperInterceptor implements WrapperInterceptor<RegisterInvokeData, Boolean> {

    @Autowired
    private Config config;

    @Autowired
    private DataExchanger boltDataExchanger;

    @Override
    public Boolean invokeCodeWrapper(WrapperInvocation<RegisterInvokeData, Boolean> wrapperInvocation) throws Exception {

        RegisterInvokeData registerInvokeData = wrapperInvocation.getParameterSupplier().get();
        BaseInfo baseInfo = (BaseInfo) registerInvokeData.getStoreData();

        Server server = boltDataExchanger.getServer(config.getServerPort());

        Channel channel = server.getChannel(baseInfo.getClientUrl());

        if (channel == null) {
            throw new RequestChannelClosedException(String.format("Register address %s  channel closed", baseInfo.getClientUrl()));
        }
        return wrapperInvocation.proceed();
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
